package sk.tuke.lara.masplc.agents;

import jade.core.behaviours.CyclicBehaviour;
import jade.lang.acl.ACLMessage;
import jade.lang.acl.MessageTemplate;
import sk.tuke.lara.masplc.Conversations;
import sk.tuke.lara.masplc.utils.CommunicationUtils;
import sk.tuke.lara.masplc.utils.MsgTemplateFactory;

public class SetPlcRequestBehaviour extends CyclicBehaviour {

    private static final long serialVersionUID = -9138156882412785201L;
    private MessageTemplate setPlcMT;
    private PlcAgent myAgent;

    public SetPlcRequestBehaviour(PlcAgent a) {
        this.myAgent = a;
        setPlcMT = MsgTemplateFactory.matchConversiation(Conversations.SET_PLC, a.getAID());
    }

    @Override
    public void action() {
        ACLMessage msg = myAgent.receive(setPlcMT);
        if (msg != null) {
            PlcAgentDTO fromJson = CommunicationUtils.fromJson(msg.getContent(), PlcAgentDTO.class);

            System.out.println(" setting CONTROL to " + fromJson.getPozadovanyVykon() + " [W]");
            myAgent.aktualniVykon = fromJson.getPozadovanyVykon();
            myAgent.changeState();

            ACLMessage response = new ACLMessage(ACLMessage.AGREE);
            response.setConversationId(msg.getConversationId());
            response.addReceiver(msg.getSender());
            myAgent.send(response);

        } else {
            // wait for others
            block();
        }
    }
}
